<template>
  <div class="view-fill">
    <div v-if="!modifyInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        :title="title"
        :btn-list="fullInfo.btnList"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canComplete"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="canRevoke" @click="retract">撤回</el-button>
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information
              :info="infoList"
              :label-width="infoList.labelWidth"
            ></basic-information>
          </div>
        </div>
        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <div class="flex_full_item">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :summary="true"
                  :check-box="false"
                  :tab-index="true"
                  :summary-field-list="tableInfo.summaryFieldList"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :isDynamic="true"
                >
                </page-table>
              </div>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <!-- 新增或修改 -->
    <use-application-modify
      v-if="modifyInfo.visible"
      :orderId="modifyInfo.id"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      saveFrom=""
      :fromType="modifyInfo.fromType"
      :storeOrderId="modifyInfo.storeOrderId"
      :storeOrderNo="modifyInfo.storeOrderNo"
      :useReturnImportStore="modifyInfo.useReturnImportStore"
      @callback="applicatoncallback"
    />
    <export
      v-if="exportInfo.visible"
      :id="exportInfo.id"
      v-model:visible="exportInfo.visible"
      :title="exportInfo.title"
      @callback="exprotcallback"
    />
    <individual-details
      v-if="individualInfo.visible"
      v-model:show-dialog="individualInfo.visible"
      :query="individualInfo.query"
      :info="individualInfo.info"
    />
  </div>
</template>

<script setup name="useReturnApplicationDetails">
import BasicInformation from '../../../components/BasicInformation/index'
import {
  getUseReturnApplicationDetailCustomizeList,
  detailUseReturnApplication,
  exportUseReturnApplication,
} from '@/api/use.js'
import PageTable from '../../../components/PageTable/index'
import UseApplicationModify from './modify'
import { orderAffairAll } from '../../../api/affair'
import Export from './export'
import IndividualDetails from './IndividualDetails'
import { getCustomizeSetting } from '@/api/customize'
import {
  submitUseReturnApplication,
  retractUseReturnApplication,
} from '@/api/use'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const Tooltip = defineAsyncComponent(() => import('@/components/Tooltip/index'))

const props = defineProps(['visible', 'id'])

const title = '领用退回单详情'
const infoList = reactive({
  data: {},
  fieldList: [
    { label: '申请单号', value: 'orderNo', type: 'text' },
    { label: '退回人', value: 'applicationUserName', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '退回部门', value: 'deptName', type: 'text' },
    { label: '退入部门', value: 'storeDeptName', type: 'text' },
    { label: '退出仓库', value: 'depotName', type: 'text' },
    { label: '退入仓库', value: 'storeDepotName', type: 'text' },
    { label: '退回日期', value: 'applicationTime', type: 'text' },
    { label: '创建人', value: 'createUserName', type: 'text' },
    { label: '创建时间', value: 'createTime', type: 'text' },
    { label: '更新人', value: 'updateUserName', type: 'text' },
    { label: '更新时间', value: 'updateTime', type: 'text' },
    {
      label: '是否寄售业务',
      value: 'isConsignBusinessValue',
      type: 'text',
      show: proxy.$store.state.permission.systemConfig.is_consign_business == 1,
    },
    { label: '业务日期', value: 'businessDate', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
  labelWidth: '130px',
})
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '80',
    btList: [
      {
        label: '个体详情',
        event: showDetail,
        show: true,
      },
    ],
  },
})
const fullInfo = reactive({
  btnList: [
    {
      label: '导出excel',
      event: exportExcel,
      show: proxy.$permission('useReturnApplication:exportExcel'),
    },
  ],
})
const exportInfo = reactive({
  visible: false,
  title: '领用退回单出库',
  id: '',
})

const filterInfo = reactive({
  query: {
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id,
      },
    },
    queryParams: {},
    customizeUserVO: {},
  },
})
const affairTableInfo = reactive({
  api: orderAffairAll,
  query: {
    orderType: 33,
    orderId: props.id,
    sort: 'operate_time desc,operate_type desc',
  },
})
//更新相关
const modifyInfo = reactive({
  visible: false,
  title: '',
  id: '',
  fromType: '',
  storeOrderId: '',
  storeOrderNo: '',
  useReturnImportStore: '',
})
const individualInfo = reactive({
  visible: false,
  query: {},
  info: {},
})

const canComplete = computed(() => {
  return proxy.$permission('useReturnApplication:print')
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emit('update:visible', newValue) // 更新父组件visible
  },
})
const canUpdate = computed(() => {
  return (
    proxy.$permission('useReturnApplication:update') &&
    infoList.data.status === 1
  )
})
const canSubmit = computed(() => {
  return (
    proxy.$permission('useReturnApplication:submit') &&
    infoList.data.status === 1
  )
})
const canRevoke = computed(() => {
  return (
    proxy.$permission('useReturnApplication:retract') &&
    infoList.data.status === 2
  )
})

watch(
  () => props.visible,
  (newVal) => {
    showDialog.value = newVal
  },
  {
    immediate: true,
  }
)
watch(
  () => exportInfo.visible,
  (val) => {
    if (!val) {
      getMain()
    }
  }
)
watch(
  () => modifyInfo.visible,
  (val) => {
    if (!val) {
      getMain()
    }
  }
)

let obj = {
  orderNo: {
    label: '单号',
    value: 'orderNo',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  price: {
    label: '单价',
    value: 'price',
    minWidth: '150px',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useReturnApplication:price'),
    hidden: true,
  },
  sumAmount: {
    label: '总金额',
    value: 'sumAmount',
    type: 'column',
    formatter: proxy.$fn.TripartiteMethod,
    permission: !proxy.$permission('useReturnApplication:price'),
    hidden: true,
  },
  defaultSupplierPrice: {
    label: '默认供应商价格',
    value: 'defaultSupplierPrice',
    type: 'column',
    componentType: 'price',
    permission: !proxy.$permission('useReturnApplication:price'),
    formatter: proxy.$fn.TripartiteMethod,
    hidden: true,
    show: false,
  },
}
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

//提交
function submit() {
  let ids = []
  ids.push(infoList.data.id)
  submitUseReturnApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}
function retract() {
  let ids = []
  ids.push(infoList.data.id)
  retractUseReturnApplication(ids).then((resp) => {
    if (resp && resp.success) {
      getMain()
    }
  })
}

function returnBack() {
  emit('returnBack', false)
}

//个体详情
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.id,
    },
  }
  individualInfo.info = row
  individualInfo.visible = true
}
// 编辑
function update() {
  modifyInfo.id = props.id
  modifyInfo.visible = true
  modifyInfo.title = '修改领用退回单'
  modifyInfo.fromType = ''
  modifyInfo.storeOrderId = ''
  modifyInfo.storeOrderNo = ''
  modifyInfo.useReturnImportStore =
    proxy.$store.state.permission.systemConfig.use_application_return_import_store_order.toString()
  if (infoList.data.sourceType === 20) {
    modifyInfo.fromType = 'useStore'
    modifyInfo.storeOrderId = infoList.data.sourceId
    modifyInfo.storeOrderNo = infoList.data.sourceOrderNo
  }
}

function applicatoncallback() {
  getMain()
}

function getList() {
  getUseReturnApplicationDetailCustomizeList(filterInfo.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.data = resp.data
    }
  })
}
function setBtnStatus(data) {
  if (fullInfo.btnList[1]) {
    if (data.status !== 1 && proxy.$permission('useReturnApplication:print')) {
      fullInfo.btnList[1].show = true
    } else {
      fullInfo.btnList[1].show = false
    }
  }
  if (
    data.status !== 1 &&
    proxy.$permission('useReturnApplication:exportExcel')
  ) {
    fullInfo.btnList[0].show = true
  } else {
    fullInfo.btnList[0].show = false
  }
}
//导出excel
function exportExcel() {
  exportUseReturnApplication(filterInfo.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}

const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'useReturnApplicationDetail',
    deptId: infoList.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            applicationId: infoList.data.id,
            orderId: infoList.data.id,
            orderNo: infoList.data.orderNo,
          },
          callback: printCallback,
          printCount: true,
          data: {},
        })
      }
    }
  })
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      applicationId: infoList.data.id,
      orderId: infoList.data.id,
      orderNo: infoList.data.orderNo,
    },
    callback: printCallback,
    printCount: true,
    data: {},
  })
  popoverVisible.value = false
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.data.orderNo,
      orderId: infoList.data.id,
      tempCode: 'useReturnApplicationDetail',
      orderType: 33,
    })
  } catch (error) {}
}
function getMain() {
  detailUseReturnApplication(props.id).then((resp) => {
    if (resp && resp.success) {
      infoList.data = resp.data
      getList()
      setBtnStatus(resp.data)
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      'useReturnApplicationOrderDetail-com.slip.spd.entity.vo.use.UseReturnApplicationOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.query.customizeUserVO = res.data
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      )
      getMain()
    }
  })
}
</script>

<style scoped></style>
